let cards = JSON.parse(localStorage.getItem('cards')) || [];
let qrCodeElement = null;

function addCard() {
    const cardNum = prompt('请输入卡号:');
    const cardPass = prompt('请输入密码:');
    const amount = prompt('请输入金额:');

    if (cardNum && cardPass && amount) {
        const card = {
            id: Date.now(),
            cardNum,
            cardPass,
            amount,
            status: '正常'
        };
        cards.push(card);
        localStorage.setItem('cards', JSON.stringify(cards));
        refreshTable();
    }
}

function generateQRCode() {
    const selectedCard = cards.find(card => card.status === '已绑定');
    if (selectedCard) {
        fetch('/generate_qr', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                cardNum: selectedCard.cardNum,
                cardPass: selectedCard.cardPass
            }),
        })
        .then(response => response.json())
        .then(data => {
            if (qrCodeElement) {
                qrCodeElement.remove();
            }
            const qrCodeContainer = document.createElement('div');
            qrCodeContainer.className = 'qr-code-container';
            qrCodeContainer.innerHTML = `<img src="data:image/png;base64,${data.qr_code}" alt="QR Code">`;
            const table = document.querySelector('#cardTable');
            table.parentNode.appendChild(qrCodeContainer);
            qrCodeElement = qrCodeContainer;
        })
        .catch(error => console.error('Error generating QR code:', error));
    } else {
        alert('没有已绑定的卡');
    }
}

function refreshTable() {
    const tableBody = document.querySelector('#cardTable tbody');
    tableBody.innerHTML = '';

    cards.forEach((card, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><input type="checkbox"></td>
            <td>${index + 1}</td>
            <td>${card.cardNum}</td>
            <td>${card.cardPass}</td>
            <td>${card.amount}</td>
            <td>${card.status}</td>
        `;
        tableBody.appendChild(row);
    });
}

// 初始化表格
refreshTable();